package tongxin1;

/*
* 三条线程通信
* */
public class test2Santiaoxianchengtongxin {
    public static void main(String[] args) {
        Printer2 printer2 = new Printer2();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    synchronized (Printer2.class){
                        try {
                            printer2.print1();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    synchronized (Printer2.class){
                        try {
                            printer2.print2();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    synchronized (Printer2.class){
                        try {
                            printer2.print3();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        }).start();
    }
}

class Printer2{
    private int flag = 1;
    public void print1() throws InterruptedException {
        while (flag != 1){// 这里是while处理， 不能单独判断if。 --- 因为要是if， 所有人解禁的时候，if已经执行过，就向下继续执行。 而如果是while，就会从新判断一次。
            Printer2.class.wait();
        }
        System.out.println("a");
        flag = 2;

        Printer2.class.notifyAll(); // 这里是 解禁所有 - 不然就会死胡同，卡住。

    }
    public void print2() throws InterruptedException {
        while(flag != 2){
            Printer2.class.wait();
        }
        System.out.println("b");
        flag = 3;
        Printer2.class.notifyAll();

    }
    public void print3() throws InterruptedException {
        while(flag != 3){
            Printer2.class.wait();
        }
        System.out.println("c");
        flag = 1;
        Printer2.class.notifyAll();
    }
}
